﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using BAL;
using Common;
using Common.Modules;
using Entity;

namespace Web.ChartReport
{
    public partial class DownStudent : System.Web.UI.Page
    {
        protected int examroomid = 0, studentid = 0;
        protected bool isquery = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!UserValidate.CheckLogin(this.Request, "StatistScore"))
            {
                if (!UserValidate.CheckQuery())
                {
                    Response.Write("<script type=\"text/javascript\">top.location.href='login.aspx';</script>");
                    Response.Redirect("login.aspx");
                    Response.End();
                }
                else
                {
                    isquery = true;
                }
            }
            if (isquery)
            {
                studentid = int.Parse(HttpContext.Current.Session["QueryStudentId"] as string);
            }
            else if (!PageValidate.QueryStringIsEmpty("studentid"))
            {
                try
                {
                    studentid = int.Parse(PageValidate.QueryString("studentid"));
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    Response.End();
                }
            }
            if (!PageValidate.QueryStringIsEmpty("examroomid"))
            {
                try
                {
                    examroomid = int.Parse(PageValidate.QueryString("examroomid"));
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    Response.End();
                }
            }
            if (!IsPostBack)
            {
                if (studentid > 0 && examroomid > 0)
                {
                    DownLoad();
                }
            }
        }

        private void DownLoad()
        {
            ExamRoomInfo examroomInfo = ExamRoom.GetSingleInfo(examroomid);
            IList<StudentScoreExtendInfo> infos = new List<StudentScoreExtendInfo>();
            infos = StudentScoreExtend.GetList(examroomInfo.Id, 0, 0, 0, 0, 0, 0, 0);
            StudentScoreExtendInfo myInfo = infos.Single(t => t.StudentId == studentid);

            GraphMaker gm = new GraphMaker();
            PdfMaker pm = new PdfMaker();
            pm.Initialize();

            pm.AddStudentCover(myInfo.Name, ConfigurationManager.AppSettings["InstitutionName"]);

            pm.AddHeader("课业诊断报告");
            #region 综合评价

            pm.AddChapter("综合评价");
            {
                pm.AddSection("考试成绩");
                DataTable table1 = new DataTable("考试成绩概表");
                table1.Columns.Add("你的成绩");
                table1.Columns.Add("班级平均分");
                table1.Columns.Add("班级最高分");
                table1.Columns.Add("班级考试人数");
                table1.Columns.Add("年级平均分");
                table1.Columns.Add("年级最高分");
                table1.Columns.Add("年级考试人数");
                table1.Columns.Add("学区平均分");
                table1.Columns.Add("学区最高分");
                table1.Columns.Add("学区考试人数");
                var row = table1.NewRow();
                row[0] = myInfo.CountScore;
                table1.Rows.Add(row);
                {
                    decimal count = infos.Where(t => t.ClassId == myInfo.ClassId).Sum(t => t.CountScore);
                    StudentScoreExtendInfo info = infos.Where(t => t.ClassId == myInfo.ClassId).OrderByDescending(t => t.CountScore).First();
                    int rencount = infos.Where(t => t.ClassId == myInfo.ClassId).Count();
                    row[1] = Math.Round((count / rencount), 1).ToString();
                    row[2] = info.CountScore.ToString();
                    row[3] = rencount.ToString();
                }
                {
                    decimal count = infos.Where(t => t.GradeId == myInfo.GradeId).Sum(t => t.CountScore);
                    StudentScoreExtendInfo info = infos.Where(t => t.GradeId == myInfo.GradeId).OrderByDescending(t => t.CountScore).First();
                    int rencount = infos.Where(t => t.GradeId == myInfo.GradeId).Count();
                    row[4] = Math.Round((count / rencount), 1).ToString();
                    row[5] = info.CountScore.ToString();
                    row[6] = rencount.ToString();
                }
                {
                    decimal count = infos.Where(t => t.AreaId == myInfo.AreaId).Sum(t => t.CountScore);
                    StudentScoreExtendInfo info = infos.Where(t => t.AreaId == myInfo.AreaId).OrderByDescending(t => t.CountScore).First();
                    int rencount = infos.Where(t => t.AreaId == myInfo.AreaId).Count();
                    row[7] = Math.Round((count / rencount), 1).ToString();
                    row[8] = info.CountScore.ToString();
                    row[9] = rencount.ToString();
                }
                pm.AddPdfTable(table1, new float[] { 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f });
                {
                    GraphData graphData = new GraphData();
                    graphData.Type = AnalyticsType.Bar;
                    graphData.Title = "个人成绩比较";
                    graphData.XAxisTitle = "";
                    graphData.YAxisTitle = "平均分";
                    graphData.XAxisDatasList = new List<double[]>();
                    graphData.XAxisDatasList.Add(new double[] { 5, 10, 15, 20 });
                    graphData.YAxisDatasList = new List<double[]>();
                    graphData.YAxisDatasList.Add(new double[]{
                        double.Parse(row[0].ToString()),
                        double.Parse(row[1].ToString()),
                        double.Parse(row[4].ToString()),
                        double.Parse(row[7].ToString())}
                        );
                    graphData.XNames = new string[] { "个人", "班级", "年级", "学区" };
                    Image img = gm.Draw(graphData);
                    pm.AddGraph(img, "个人成绩比较");
                }
                pm.AddSection("评卷点评");
                pm.AddSimpleParagraph(examroomInfo.Comment);
            }

            #endregion

            #region 知识领域得分率

            pm.AddChapter("知识领域得分率");
            {
                DataTable table = new DataTable("知识领域得分统计表");
                table.Columns.Add("序号");
                table.Columns.Add("知识领域");
                table.Columns.Add("题量");
                table.Columns.Add("分值");
                table.Columns.Add("个人得分");
                table.Columns.Add("个人得分率(%)");
                table.Columns.Add("班级得分率(%)");
                table.Columns.Add("年级得分率(%)");
                table.Columns.Add("学区得分率(%)");

                IList<KnowledgeInfo> listKnowledge = Knowledge.GetKnowledgeInfosBySubjectId(myInfo.SubjectId)
                    .Where(t => t.Keyword.Length == 1).ToList();
                IList<QuestionInfo> listQuestion = Question.GetQuestions(examroomInfo.Id, "", "", "", "", "", "", "", "", "", 0, 0);
                foreach (KnowledgeInfo know in listKnowledge)
                {
                    DataRow row = table.NewRow();
                    table.Rows.Add(row);
                    row[0] = table.Rows.Count;

                    decimal questScoreCount = 0;
                    IList<int> questIds = new List<int>();
                    foreach (QuestionInfo quest in listQuestion)
                    {
                        if (quest.KnowId == know.Id)
                        {
                            questScoreCount += quest.Score;
                            questIds.Add(quest.Id);
                        }
                        else if (know.ChildKnowledgeInfos.Count > 0)
                        {
                            IList<int> ids = know.ChildKnowledgeInfos.Select(t => t.Id).ToList();
                            if (GetArray<int>.Get(ids).Contains(quest.KnowId))
                            {
                                questScoreCount += quest.Score;
                                questIds.Add(quest.Id);
                            }
                            else
                            {
                                foreach (KnowledgeInfo n in know.ChildKnowledgeInfos)
                                {
                                    if (n.ChildKnowledgeInfos.Count > 0)
                                    {
                                        IList<int> childids = n.ChildKnowledgeInfos.Select(t => t.Id).ToList();
                                        if (GetArray<int>.Get(childids).Contains(quest.KnowId))
                                        {
                                            questScoreCount += quest.Score;
                                            questIds.Add(quest.Id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (questIds.Count == 0)
                    {
                        continue;
                    }
                    decimal myScore = 0, classScore = 0, gradeScore = 0, areaScore = 0;
                    int classNum = 0, gradeNum = 0, areaNum = 0;
                    foreach (StudentScoreExtendInfo info in infos)
                    {
                        IList<ScoreInfo> scoreInfos = ScoreHelper.GetScoreList(info.QuestItemScore);
                        scoreInfos = scoreInfos.Where(t => GetArray<int>.Get(questIds).Contains(t.Id)).ToList();
                        decimal score = 0;
                        foreach (ScoreInfo scoreInfo in scoreInfos)
                        {
                            if (!PageValidate.IsEmpty(scoreInfo.Score))
                            {
                                score += decimal.Parse(scoreInfo.Score);
                            }
                        }
                        if (info.StudentId == myInfo.StudentId)
                        {
                            myScore = score;
                        }
                        if (info.ClassId == myInfo.ClassId)
                        {
                            classScore += score;
                            classNum++;
                        }
                        if (info.GradeId == myInfo.GradeId)
                        {
                            gradeScore += score;
                            gradeNum++;
                        }
                        if (info.AreaId == myInfo.AreaId)
                        {
                            areaScore += score;
                            areaNum++;
                        }
                    }
                    row[1] = know.Name;
                    row[2] = listQuestion.Count;
                    row[3] = questScoreCount;
                    row[4] = myScore;
                    row[5] = Math.Round(myScore / questScoreCount * 100);
                    row[6] = Math.Round(classScore / (questScoreCount * classNum) * 100);
                    row[7] = Math.Round(gradeScore / (questScoreCount * gradeNum) * 100);
                    row[8] = Math.Round(areaScore / (questScoreCount * areaNum) * 100);
                }
                pm.AddPdfTable(table, new float[] { 30f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f });
                var image = gm.Draw(table, table.Columns[1],
                    new DataColumn[] { table.Columns[5], table.Columns[6], table.Columns[7], table.Columns[8] },
                    "得分率(%)", AnalyticsType.Bar);
                pm.AddGraph(image, table.TableName);
            }

            #endregion

            #region 考察点得分率

            pm.AddChapter("考察点得分率");

            #endregion

            #region 能力维度得分率

            pm.AddChapter("能力维度得分率");

            #endregion

            #region 应试能力 — 题型表现

            pm.AddChapter("应试能力 — 题型表现");

            #endregion

            #region 应试能力 — 难度表现

            pm.AddChapter("应试能力 — 难度表现");

            #endregion

            #region 学生未得满分的题目汇总

            pm.AddChapter("学生未得满分的题目汇总");

            #endregion

            #region 参考答案

            pm.AddChapter("参考答案");

            #endregion

            pm.SavePdf();
        }
    }
}